package cn.lesaas.esb.component.tuxedo;

import java.net.ConnectException;

import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.impl.DefaultMessage;
import org.apache.camel.impl.DefaultProducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import bea.jolt.JoltRemoteService;
import bea.jolt.JoltSession;
import bea.jolt.JoltSessionAttributes;
import bea.jolt.ServiceException;

public class TuxedoProducer extends DefaultProducer {
	private static final Logger LOG = LoggerFactory.getLogger(TuxedoProducer.class);
	private TuxedoConfiguration configuration;
	private JoltSession session;

	public TuxedoProducer(Endpoint endpoint, TuxedoConfiguration configuration) {
		super(endpoint);
		this.configuration = configuration;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	private void connect() throws Exception {
		LOG.info("connect to remote tuxedo server");
		JoltSessionAttributes sattr = new JoltSessionAttributes();
		
		String address = "//" + configuration.getHost() + ":" + configuration.getPort();
		sattr.setString(JoltSessionAttributes.APPADDRESS, address);

		String userName = "";
		String userRole = "";
		String userPassword = "";
		String appPassword = "";

		int recvTimeOut = 30;
		int sendTimeOut = 30;

		switch (sattr.checkAuthenticationLevel()) {
		case JoltSessionAttributes.NOAUTH:
			break;
		case JoltSessionAttributes.APPASSWORD:
			// appPassword = zjxx.gett();
			break;
		case JoltSessionAttributes.USRPASSWORD:
			// userName = zjxx.getUserName();
			// userPassword = zjxx.getUserPassword();
			// appPassword = zjxx.getAppPassword();
			break;
		default:
			break;
		}

		sattr.setInt(JoltSessionAttributes.IDLETIMEOUT, 0);
		sattr.setInt(JoltSessionAttributes.RECVTIMEOUT, recvTimeOut);
		sattr.setInt(JoltSessionAttributes.SENDTIMEOUT, sendTimeOut);
		//sattr.setInt(JoltSessionAttributes.SESSIONTIMEOUT, 0);

		session = new JoltSession(sattr, userName, userRole, userPassword, appPassword);
	}

	@Override
	public void process(Exchange exchange) throws Exception {
		if (session == null) {
			connect();
		}
		
		String body = exchange.getIn().getBody(String.class);

		if (session == null) {
			LOG.error("can not connect : " + "Address");
			new ConnectException("Cannot connect to " + "");
		}

		String serviceName = "TOUPPER";
		// Exchange body
		String req = null;
		JoltRemoteService jrs = new JoltRemoteService(serviceName, session);
		jrs.setString("STRING", body);
		// jrs.setBytes("CARRAY", sendBuffer, sendBuffer.length);

		String recvStr;

		try {
			jrs.call(null);
			recvStr = jrs.getStringDef("STRING", null);
			// jrs.setBytes("CARRAY", sendBuffer, sendBuffer.length);
			exchange.getOut().setBody(recvStr);
		} catch (ServiceException e) {
			throw new Exception(e.getMessage());
		} finally {
			jrs.clear();
			jrs.done();
			jrs = null;
		}

	}
}
